﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraController : MonoBehaviour {

	public Transform avatar;
	public float maxDistance = 20F;
	public float minDistance = 6F;
	public float yMin = 3F;
	public float yMax = 50F;
	public float ySpeed = 1F;
	public float xSpeed = 4F;
	public float heightOffset;

	private float currentY = 25F;
	private float currentX = 0F;
	private Quaternion rotation;


	private float distSlope;
	private float b;
	private float distance;
	private Camera thisCam;

	void Start () 
	{	
		currentY = (yMax+yMin)/2;
		currentX = avatar.eulerAngles.y;
		thisCam = this.GetComponent<Camera> ();
		distSlope = (maxDistance-minDistance)/(yMax-yMin);
		b = - yMax * distSlope + maxDistance;
		distance = distSlope * currentY + b;
	}

	void Update()
	{

		if (Input.GetKey (KeyCode.E))
		{	
			currentY += ySpeed;
		}

		if (Input.GetKey (KeyCode.D))
		{
			currentY -= ySpeed;
		}

		if (Input.GetKey (KeyCode.S)) 
		{
			currentX += xSpeed;
		}

		if (Input.GetKey (KeyCode.F))
		{
			currentX -= xSpeed;
		}

		currentY = Mathf.Clamp(currentY, yMin, yMax); 


		distance = distSlope * currentY + b;
		Vector3 dir = new Vector3(0, 0, -distance);
		rotation = Quaternion.Euler(currentY, currentX, 0);
		thisCam.transform.position = avatar.position + rotation*dir;
		thisCam.transform.LookAt(new Vector3(avatar.position.x, avatar.position.y + heightOffset , avatar.position.z));
	}
}
